<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button
            v-if="userStore.isAdmin || userStore.isTeacher"
            type="primary"
            @click="handleCreate"
          >
            新增用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="68px">
        <el-form-item label="用户名">
          <el-input
            v-model="queryForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="queryForm.roleType"
            placeholder="请选择角色"
            clearable
            style="width: 150px"
          >
            <el-option label="管理员" value="ADMIN" />
            <el-option label="教师" value="TEACHER" />
            <el-option label="学生" value="STUDENT" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="roleType" label="角色" width="100">
          <template #default="{ row }">
            <el-tag
              :type="
                (row.roleType || '').toUpperCase() === 'ADMIN' ? 'danger' :
                (row.roleType || '').toUpperCase() === 'TEACHER' ? 'warning' : 'success'
              "
            >
              {{
                (row.roleType || '').toUpperCase() === 'ADMIN' ? '管理员' :
                (row.roleType || '').toUpperCase() === 'TEACHER' ? '教师' : '学生'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column label="学院" width="120">
          <template #default="{ row }">
            {{ getCollegeName(row.collegeId) }}
          </template>
        </el-table-column>
        <el-table-column label="专业" width="120">
          <template #default="{ row }">
            {{ getMajorName(row.classId) }}
          </template>
        </el-table-column>
        <el-table-column label="班级" width="120">
          <template #default="{ row }">
            {{ getClassName(row.classId) }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phonenumber" label="手机号" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin || userStore.isTeacher"
              link
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              link
              type="danger"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            :disabled="isEdit"
            placeholder="请输入用户名"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="userForm.realName"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        
        <el-form-item label="角色类型" prop="roleType">
          <el-select
            v-model="userForm.roleType"
            placeholder="请选择角色"
            style="width: 100%"
            @change="handleRoleTypeChange"
          >
            <el-option label="管理员" value="ADMIN" />
            <el-option label="教师" value="TEACHER" />
            <el-option label="学生" value="STUDENT" />
          </el-select>
        </el-form-item>
        
        <!-- 学生专属字段：学院、专业、班级 -->
        <el-form-item 
          v-if="userForm.roleType === 'STUDENT'" 
          label="学院" 
          prop="collegeId"
        >
          <el-select
            v-model="userForm.collegeId"
            placeholder="请选择学院"
            style="width: 100%"
            filterable
            clearable
            @change="handleCollegeChange"
          >
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item 
          v-if="userForm.roleType === 'STUDENT' && userForm.collegeId" 
          label="专业" 
          prop="majorId"
        >
          <el-select
            v-model="userForm.majorId"
            placeholder="请选择专业"
            style="width: 100%"
            filterable
            clearable
            :loading="loadingMajors"
            @change="handleMajorChange"
          >
            <el-option
              v-for="major in majorOptions"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item 
          v-if="userForm.roleType === 'STUDENT' && userForm.majorId" 
          label="班级" 
          prop="classId"
        >
          <el-select
            v-model="userForm.classId"
            placeholder="请选择班级"
            style="width: 100%"
            filterable
            clearable
            :loading="loadingClasses"
          >
            <el-option
              v-for="classItem in classOptions"
              :key="classItem.id"
              :label="classItem.name"
              :value="classItem.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            v-model="userForm.phonenumber"
            placeholder="请输入手机号"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="用户详情"
      width="600px"
    >
      <el-descriptions :column="2" border v-if="viewUser">
        <el-descriptions-item label="ID">{{ viewUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ viewUser.username }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ viewUser.realName }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag
            :type="
              (viewUser.roleType || '').toUpperCase() === 'ADMIN' ? 'danger' :
              (viewUser.roleType || '').toUpperCase() === 'TEACHER' ? 'warning' : 'success'
            "
          >
            {{
              (viewUser.roleType || '').toUpperCase() === 'ADMIN' ? '管理员' :
              (viewUser.roleType || '').toUpperCase() === 'TEACHER' ? '教师' : '学生'
            }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewUser.sex }}</el-descriptions-item>
        <el-descriptions-item label="学院">
          {{ getCollegeName(viewUser.collegeId) }}
        </el-descriptions-item>
        <el-descriptions-item label="专业">
          {{ getMajorName(viewUser.classId) }}
        </el-descriptions-item>
        <el-descriptions-item label="班级">
          {{ getClassName(viewUser.classId) }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewUser.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ viewUser.phonenumber }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(viewUser.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(viewUser.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store/user'
import { getUserList, createUser, updateUser, deleteUser, getUserById } from '../../api/user'
import { getAllColleges, type CollegeInfo } from '../../api/college'
import { getMajorsByCollege, type MajorInfo } from '../../api/major'
import { getClassesByMajor, type ClassInfo } from '../../api/class'
import { getClassById } from '../../api/class'
import { getMajorById } from '../../api/major'
import { getCollegeById } from '../../api/college'

const userStore = useUserStore()

const loading = ref(false)
const submitLoading = ref(false)
const userList = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const currentUserId = ref(null)
const viewUser = ref(null)

const queryForm = reactive({
  username: '',
  roleType: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const userFormRef = ref(null)
const userForm = reactive({
  username: '',
  password: '',
  realName: '',
  roleType: 'STUDENT',
  sex: '男',
  email: '',
  phonenumber: '',
  collegeId: null as number | null,
  majorId: null as number | null,
  classId: null as number | null
})

// 学院、专业、班级选项
const collegeOptions = ref<CollegeInfo[]>([])
const majorOptions = ref<MajorInfo[]>([])
const classOptions = ref<ClassInfo[]>([])
const loadingMajors = ref(false)
const loadingClasses = ref(false)

// 所有专业和班级的映射（用于显示）
const allMajorsMap = ref<Record<number, MajorInfo>>({})
const allClassesMap = ref<Record<number, ClassInfo>>({})
const allCollegesMap = ref<Record<number, CollegeInfo>>({})

const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (isEdit.value) {
          // 编辑模式下，密码可以为空
          callback()
        } else {
          // 新增模式下，密码必填
          if (!value) {
            callback(new Error('请输入密码'))
          } else if (value.length < 6) {
            callback(new Error('密码长度不能少于6位'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  roleType: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ],
  collegeId: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (userForm.roleType === 'STUDENT' && !value) {
          callback(new Error('请选择学院'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  classId: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (userForm.roleType === 'STUDENT' && !value) {
          callback(new Error('请选择班级'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑用户' : '新增用户'
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const queryParams: any = {
      username: queryForm.username || undefined,
      page: pagination.page,
      size: pagination.size
    }
    // 确保roleType是大写
    if (queryForm.roleType) {
      queryParams.roleType = queryForm.roleType.toUpperCase()
    }
    const res = await getUserList(queryParams)
    
    // res 就是 ApiResponse，res.data 是 PageResult，res.data.data 是列表数据
    userList.value = res.data.data || []
    pagination.total = res.data.total || 0
    
    // 加载所有相关的学院、专业、班级信息用于显示
    const collegeIds = new Set<number>()
    const classIds = new Set<number>()
    
    userList.value.forEach((user: any) => {
      if (user.collegeId) collegeIds.add(user.collegeId)
      if (user.classId) classIds.add(user.classId)
    })
    
    // 批量加载学院信息
    if (collegeIds.size > 0) {
      for (const id of collegeIds) {
        if (!allCollegesMap.value[id]) {
          try {
            const res = await getCollegeById(id)
            if (res.data) {
              allCollegesMap.value[id] = res.data
            }
          } catch (e) {
            // 静默失败
          }
        }
      }
    }
    
    // 批量加载班级信息
    for (const classId of classIds) {
      if (!allClassesMap.value[classId]) {
        try {
          const classRes = await getClassById(classId)
          if (classRes.data) {
            allClassesMap.value[classId] = classRes.data
            // 加载专业信息
            if (classRes.data.majorId && !allMajorsMap.value[classRes.data.majorId]) {
              try {
                const majorRes = await getMajorById(classRes.data.majorId)
                if (majorRes.data) {
                  allMajorsMap.value[classRes.data.majorId] = majorRes.data
                  // 如果专业有学院ID，也加载学院信息
                  if (majorRes.data.collegeId && !allCollegesMap.value[majorRes.data.collegeId]) {
                    try {
                      const collegeRes = await getCollegeById(majorRes.data.collegeId)
                      if (collegeRes.data) {
                        allCollegesMap.value[majorRes.data.collegeId] = collegeRes.data
                      }
                    } catch (e) {
                      // 静默失败
                    }
                  }
                }
              } catch (e) {
                // 静默失败
              }
            }
          }
        } catch (e) {
          // 静默失败
        }
      }
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  queryForm.username = ''
  queryForm.roleType = ''
  handleQuery()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchUserList()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchUserList()
}

// 新增
const handleCreate = () => {
  isEdit.value = false
  currentUserId.value = null
  resetUserForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  currentUserId.value = row.id
  Object.assign(userForm, {
    username: row.username,
    password: '',
    realName: row.realName || '',
    roleType: (row.roleType || 'STUDENT').toUpperCase(),
    sex: row.sex || '男',
    email: row.email || '',
    phonenumber: row.phonenumber || '',
    collegeId: row.collegeId || null,
    majorId: null,
    classId: row.classId || null
  })
  
  // 如果编辑学生且有班级ID，需要加载对应的专业和学院
  if (row.roleType === 'STUDENT' && row.classId) {
    loadClassAndMajorInfo(row.classId).then(() => {
      // 加载完班级信息后，根据专业ID过滤专业列表
      if (userForm.collegeId && userForm.majorId) {
        loadMajorsByCollege(userForm.collegeId)
      }
    })
  } else if (row.roleType === 'STUDENT' && row.collegeId) {
    // 如果有学院ID，加载专业列表
    loadMajorsByCollege(row.collegeId)
  }
  
  dialogVisible.value = true
}

// 查看
const handleView = async (id) => {
  try {
    const res = await getUserById(id)
    // res 就是 ApiResponse，res.data 是实际的用户对象
    viewUser.value = res.data
    
    // 如果用户有班级ID，加载班级和专业信息用于显示
    if (res.data.classId) {
      await loadClassAndMajorInfo(res.data.classId)
    }
    
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteUser(id)
    ElMessage.success('删除成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 学生必须选择学院和班级
    if (userForm.roleType === 'STUDENT' && (!userForm.collegeId || !userForm.classId)) {
      ElMessage.warning('学生必须选择学院和班级')
      return
    }
    
    submitLoading.value = true
    
    try {
      if (isEdit.value) {
        // 编辑：不传密码字段，除非有值
        const updateData: any = { ...userForm }
        if (!updateData.password) {
          delete updateData.password
        }
        // 确保roleType是大写
        if (updateData.roleType) {
          updateData.roleType = updateData.roleType.toUpperCase()
        }
        // 如果不是学生，清空学院和班级
        if (updateData.roleType !== 'STUDENT') {
          updateData.collegeId = null
          updateData.classId = null
        } else {
          // 学生不需要majorId，只需要collegeId和classId
          delete updateData.majorId
        }
        await updateUser(currentUserId.value, updateData)
        ElMessage.success('更新成功')
      } else {
        // 新增：确保roleType是大写
        const createData: any = { ...userForm }
        if (createData.roleType) {
          createData.roleType = createData.roleType.toUpperCase()
        }
        // 如果不是学生，清空学院和班级
        if (createData.roleType !== 'STUDENT') {
          createData.collegeId = null
          createData.classId = null
        } else {
          // 学生不需要majorId，只需要collegeId和classId
          delete createData.majorId
        }
        await createUser(createData)
        ElMessage.success('创建成功')
      }
      
      dialogVisible.value = false
      fetchUserList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 重置表单
const resetUserForm = () => {
  Object.assign(userForm, {
    username: '',
    password: '',
    realName: '',
    roleType: 'STUDENT',
    sex: '男',
    email: '',
    phonenumber: '',
    collegeId: null,
    majorId: null,
    classId: null
  })
  majorOptions.value = []
  classOptions.value = []
  userFormRef.value?.clearValidate()
}

// 角色类型变化
const handleRoleTypeChange = () => {
  // 如果不 Students，清空学院、专业、班级
  if (userForm.roleType !== 'STUDENT') {
    userForm.collegeId = null
    userForm.majorId = null
    userForm.classId = null
    majorOptions.value = []
    classOptions.value = []
  }
}

// 学院变化
const handleCollegeChange = () => {
  userForm.majorId = null
  userForm.classId = null
  majorOptions.value = []
  classOptions.value = []
  
  if (userForm.collegeId) {
    loadMajorsByCollege(userForm.collegeId)
  }
}

// 专业变化
const handleMajorChange = () => {
  userForm.classId = null
  classOptions.value = []
  
  if (userForm.majorId) {
    loadClassesByMajor(userForm.majorId)
  }
}

// 加载学院列表
const loadColleges = async () => {
  try {
    const res = await getAllColleges()
    collegeOptions.value = res.data || []
    // 建立映射
    res.data?.forEach(college => {
      allCollegesMap.value[college.id] = college
    })
  } catch (error) {
    ElMessage.error('获取学院列表失败')
  }
}

// 根据学院加载专业列表
const loadMajorsByCollege = async (collegeId: number) => {
  loadingMajors.value = true
  try {
    const res = await getMajorsByCollege(collegeId)
    majorOptions.value = res.data || []
    // 建立映射
    res.data?.forEach(major => {
      allMajorsMap.value[major.id] = major
    })
  } catch (error) {
    ElMessage.error('获取专业列表失败')
  } finally {
    loadingMajors.value = false
  }
}

// 根据专业加载班级列表
const loadClassesByMajor = async (majorId: number) => {
  loadingClasses.value = true
  try {
    const res = await getClassesByMajor(majorId)
    classOptions.value = res.data || []
    // 建立映射
    res.data?.forEach(classItem => {
      allClassesMap.value[classItem.id] = classItem
    })
  } catch (error) {
    ElMessage.error('获取班级列表失败')
  } finally {
    loadingClasses.value = false
  }
}

// 加载班级和专业信息（用于编辑时）
const loadClassAndMajorInfo = async (classId: number) => {
  try {
    const classRes = await getClassById(classId)
    const classInfo = classRes.data
    if (classInfo) {
      allClassesMap.value[classId] = classInfo
      userForm.majorId = classInfo.majorId
      
      // 加载专业信息
      if (classInfo.majorId) {
        const majorRes = await getMajorById(classInfo.majorId)
        const majorInfo = majorRes.data
        if (majorInfo) {
          allMajorsMap.value[classInfo.majorId] = majorInfo
          userForm.collegeId = majorInfo.collegeId
        }
      }
    }
  } catch (error) {
    // 静默失败
  }
}

// 获取学院名称
const getCollegeName = (collegeId: number | null | undefined) => {
  if (!collegeId) return '-'
  return allCollegesMap.value[collegeId]?.name || '-'
}

// 获取专业名称（通过班级ID）
const getMajorName = (classId: number | null | undefined) => {
  if (!classId) return '-'
  const classInfo = allClassesMap.value[classId]
  if (!classInfo) return '-'
  return allMajorsMap.value[classInfo.majorId]?.name || '-'
}

// 获取班级名称
const getClassName = (classId: number | null | undefined) => {
  if (!classId) return '-'
  return allClassesMap.value[classId]?.name || '-'
}

// 获取用户列表时加载所有学院、专业、班级的映射
const loadAllMappings = async () => {
  // 加载所有学院
  await loadColleges()
  
  // 加载所有专业和班级（通过用户列表中的ID）
  // 这里可以优化，只加载需要的
}

// 关闭对话框
const handleDialogClose = () => {
  resetUserForm()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(() => {
  loadColleges()
  fetchUserList()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

